//! # 统一配置管理模块
//!
//! 本模块定义了 RustCloud 框架中所有组件的统一配置结构体，解决配置重复定义问题。
//! 
//! ## 设计原则
//! 
//! * **单一数据源 (Single Source of Truth)** - 每个配置只在一个地方定义
//! * **模块化组织** - 配置按功能模块分组
//! * **向后兼容** - 通过重新导出保持现有API兼容性
//! * **类型安全** - 使用强类型确保配置有效性
//! * **可扩展性** - 支持配置的扩展和自定义
//!
//! ## 配置层次结构
//!
//! ```text
//! UnifiedConfig
//! ├── ServiceConfig      - 服务基本配置
//! ├── NetworkConfig      - 网络通信配置
//! ├── RegistryConfig     - 服务注册发现配置
//! ├── LoadBalancerConfig - 负载均衡配置
//! ├── CircuitBreakerConfig - 熔断器配置
//! ├── TransportConfig    - 传输层配置
//! ├── MetricsConfig      - 指标收集配置
//! ├── TracingConfig      - 链路追踪配置
//! ├── LoggingConfig      - 日志配置
//! ├── SecurityConfig     - 安全配置
//! └── GatewayConfig      - 网关配置
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;

// =============================================================================
// 统一配置根结构
// =============================================================================

/// 统一配置结构 - 所有组件配置的根容器
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnifiedConfig {
    /// 服务基本配置
    pub service: ServiceConfig,
    /// 网络通信配置
    pub network: NetworkConfig,
    /// 服务注册发现配置
    pub registry: RegistryConfig,
    /// 负载均衡配置
    pub load_balancer: LoadBalancerConfig,
    /// 熔断器配置
    pub circuit_breaker: CircuitBreakerConfig,
    /// 传输层配置
    pub transport: TransportConfig,
    /// 指标收集配置
    pub metrics: MetricsConfig,
    /// 链路追踪配置
    pub tracing: TracingConfig,
    /// 日志配置
    pub logging: LoggingConfig,
    /// 安全配置
    pub security: SecurityConfig,
    /// 网关配置（可选）
    pub gateway: Option<GatewayConfig>,
}

impl Default for UnifiedConfig {
    fn default() -> Self {
        Self {
            service: ServiceConfig::default(),
            network: NetworkConfig::default(),
            registry: RegistryConfig::default(),
            load_balancer: LoadBalancerConfig::default(),
            circuit_breaker: CircuitBreakerConfig::default(),
            transport: TransportConfig::default(),
            metrics: MetricsConfig::default(),
            tracing: TracingConfig::default(),
            logging: LoggingConfig::default(),
            security: SecurityConfig::default(),
            gateway: None,
        }
    }
}

// =============================================================================
// 服务配置
// =============================================================================

/// 服务基本配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceConfig {
    /// 服务名称
    pub name: String,
    /// 服务版本
    pub version: String,
    /// 服务描述
    pub description: Option<String>,
    /// 服务环境 (dev/test/staging/prod)
    pub environment: String,
    /// 服务标签
    pub tags: HashMap<String, String>,
    /// 服务分组
    pub group: Option<String>,
    /// 命名空间
    pub namespace: Option<String>,
}

impl Default for ServiceConfig {
    fn default() -> Self {
        Self {
            name: "rustcloud-service".to_string(),
            version: "1.0.0".to_string(),
            description: None,
            environment: "dev".to_string(),
            tags: HashMap::new(),
            group: None,
            namespace: None,
        }
    }
}

// =============================================================================
// 网络配置
// =============================================================================

/// 网络通信配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkConfig {
    /// 监听地址
    pub host: String,
    /// 监听端口
    pub port: u16,
    /// 健康检查端口
    pub health_port: Option<u16>,
    /// 指标暴露端口
    pub metrics_port: Option<u16>,
    /// TLS配置
    pub tls: Option<TlsConfig>,
}

impl Default for NetworkConfig {
    fn default() -> Self {
        Self {
            host: "0.0.0.0".to_string(),
            port: 8080,
            health_port: Some(8081),
            metrics_port: Some(9090),
            tls: None,
        }
    }
}

/// TLS配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TlsConfig {
    /// 是否启用TLS
    pub enabled: bool,
    /// 证书文件路径
    pub cert_file: String,
    /// 私钥文件路径
    pub key_file: String,
    /// CA证书文件路径（用于客户端认证）
    pub ca_file: Option<String>,
}

// =============================================================================
// 注册中心配置 (统一定义)
// =============================================================================

/// 服务注册中心配置 - 统一权威定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistryConfig {
    /// 注册中心类型 (nacos/consul/eureka/etcd/memory)
    pub registry_type: String,
    /// 注册中心地址列表
    pub endpoints: Vec<String>,
    /// 命名空间
    pub namespace: Option<String>,
    /// 服务分组
    pub group: Option<String>,
    /// 数据中心（Consul使用）
    pub datacenter: Option<String>,
    /// 认证配置
    pub auth: Option<AuthConfig>,
    /// 连接超时时间（毫秒）
    pub timeout_ms: u64,
    /// 重试次数
    pub retry_count: u32,
    /// 重试间隔（毫秒）
    pub retry_interval_ms: u64,
    /// 健康检查配置
    pub health_check: HealthCheckConfig,
    /// 额外配置参数
    pub extra: HashMap<String, serde_json::Value>,
}

impl Default for RegistryConfig {
    fn default() -> Self {
        Self {
            registry_type: "memory".to_string(),
            endpoints: vec!["127.0.0.1:8848".to_string()],
            namespace: None,
            group: None,
            datacenter: None,
            auth: None,
            timeout_ms: 5000,
            retry_count: 3,
            retry_interval_ms: 1000,
            health_check: HealthCheckConfig::default(),
            extra: HashMap::new(),
        }
    }
}

/// 认证配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthConfig {
    /// 用户名
    pub username: Option<String>,
    /// 密码
    pub password: Option<String>,
    /// API密钥
    pub api_key: Option<String>,
    /// Token
    pub token: Option<String>,
}

/// 健康检查配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthCheckConfig {
    /// 是否启用健康检查
    pub enabled: bool,
    /// 健康检查路径
    pub path: String,
    /// 检查间隔（秒）
    pub interval_seconds: u64,
    /// 超时时间（毫秒）
    pub timeout_ms: u64,
    /// 失败阈值
    pub failure_threshold: u32,
    /// 成功阈值
    pub success_threshold: u32,
}

impl Default for HealthCheckConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            path: "/health".to_string(),
            interval_seconds: 30,
            timeout_ms: 5000,
            failure_threshold: 3,
            success_threshold: 2,
        }
    }
}

// =============================================================================
// 负载均衡配置 (统一定义)
// =============================================================================

/// 负载均衡配置 - 统一权威定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoadBalancerConfig {
    /// 负载均衡策略
    pub strategy: LoadBalancerStrategy,
    /// 权重配置
    pub weights: HashMap<String, u32>,
    /// 一致性哈希配置
    pub consistent_hash: Option<ConsistentHashConfig>,
    /// 是否基于健康状态进行负载均衡
    pub health_based: bool,
    /// 粘性会话配置
    pub sticky_session: Option<StickySessionConfig>,
}

impl Default for LoadBalancerConfig {
    fn default() -> Self {
        Self {
            strategy: LoadBalancerStrategy::RoundRobin,
            weights: HashMap::new(),
            consistent_hash: None,
            health_based: true,
            sticky_session: None,
        }
    }
}

/// 负载均衡策略枚举
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LoadBalancerStrategy {
    /// 轮询
    RoundRobin,
    /// 随机
    Random,
    /// 加权轮询
    WeightedRoundRobin,
    /// 最少连接
    LeastConnections,
    /// 一致性哈希
    ConsistentHash,
    /// 最快响应
    FastestResponse,
}

/// 一致性哈希配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsistentHashConfig {
    /// 虚拟节点数量
    pub virtual_nodes: u32,
    /// 哈希函数类型
    pub hash_function: String,
}

impl Default for ConsistentHashConfig {
    fn default() -> Self {
        Self {
            virtual_nodes: 160,
            hash_function: "fnv".to_string(),
        }
    }
}

/// 粘性会话配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StickySessionConfig {
    /// 是否启用粘性会话
    pub enabled: bool,
    /// 会话标识类型 (cookie/header/ip)
    pub identifier_type: String,
    /// 会话标识名称
    pub identifier_name: String,
    /// 会话过期时间（秒）
    pub expire_seconds: u64,
}

// =============================================================================
// 熔断器配置 (统一定义)
// =============================================================================

/// 熔断器配置 - 统一权威定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CircuitBreakerConfig {
    /// 是否启用熔断器
    pub enabled: bool,
    /// 失败率阈值 (0.0-1.0)
    pub failure_rate_threshold: f64,
    /// 响应时间阈值（毫秒）
    pub response_time_threshold_ms: u64,
    /// 最小请求数阈值
    pub min_request_threshold: u32,
    /// 恢复超时时间（毫秒）
    pub recovery_timeout_ms: u64,
    /// 半开状态成功阈值
    pub half_open_success_threshold: u32,
    /// 最大并发请求数
    pub max_concurrent_requests: u32,
    /// 是否启用降级
    pub fallback_enabled: bool,
}

impl Default for CircuitBreakerConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            failure_rate_threshold: 0.5,
            response_time_threshold_ms: 5000,
            min_request_threshold: 10,
            recovery_timeout_ms: 30000,
            half_open_success_threshold: 3,
            max_concurrent_requests: 100,
            fallback_enabled: true,
        }
    }
}

// =============================================================================
// 传输层配置 (统一定义)
// =============================================================================

/// 传输层配置 - 统一权威定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransportConfig {
    /// 连接超时时间（毫秒）
    pub connect_timeout_ms: u64,
    /// 请求超时时间（毫秒）
    pub request_timeout_ms: u64,
    /// 空闲超时时间（毫秒）
    pub idle_timeout_ms: u64,
    /// 最大重试次数
    pub max_retries: u32,
    /// 重试延迟（毫秒）
    pub retry_delay_ms: u64,
    /// 连接池配置
    pub connection_pool: ConnectionPoolConfig,
    /// 保持连接活跃
    pub keep_alive: bool,
}

impl Default for TransportConfig {
    fn default() -> Self {
        Self {
            connect_timeout_ms: 5000,
            request_timeout_ms: 30000,
            idle_timeout_ms: 60000,
            max_retries: 3,
            retry_delay_ms: 1000,
            connection_pool: ConnectionPoolConfig::default(),
            keep_alive: true,
        }
    }
}

/// 连接池配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionPoolConfig {
    /// 最大连接数
    pub max_connections: u32,
    /// 最小连接数
    pub min_connections: u32,
    /// 连接超时时间（毫秒）
    pub connection_timeout_ms: u64,
    /// 最大空闲时间（毫秒）
    pub max_idle_time_ms: u64,
}

impl Default for ConnectionPoolConfig {
    fn default() -> Self {
        Self {
            max_connections: 100,
            min_connections: 10,
            connection_timeout_ms: 5000,
            max_idle_time_ms: 300000,
        }
    }
}

// =============================================================================
// 指标收集配置
// =============================================================================

/// 指标收集配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricsConfig {
    /// 是否启用指标收集
    pub enabled: bool,
    /// 指标格式 (prometheus/json)
    pub format: String,
    /// 暴露路径
    pub path: String,
    /// 收集间隔（秒）
    pub collection_interval_seconds: u64,
    /// 自定义指标
    pub custom_metrics: Vec<String>,
}

impl Default for MetricsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            format: "prometheus".to_string(),
            path: "/metrics".to_string(),
            collection_interval_seconds: 15,
            custom_metrics: Vec::new(),
        }
    }
}

// =============================================================================
// 链路追踪配置
// =============================================================================

/// 链路追踪配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TracingConfig {
    /// 是否启用链路追踪
    pub enabled: bool,
    /// 追踪系统类型 (jaeger/zipkin/otlp)
    pub tracer_type: String,
    /// 追踪服务端点
    pub endpoint: Option<String>,
    /// 采样率 (0.0-1.0)
    pub sampling_rate: f64,
    /// 批量发送配置
    pub batch_config: BatchConfig,
}

impl Default for TracingConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            tracer_type: "jaeger".to_string(),
            endpoint: None,
            sampling_rate: 0.1,
            batch_config: BatchConfig::default(),
        }
    }
}

/// 批量发送配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchConfig {
    /// 批量大小
    pub batch_size: u32,
    /// 批量超时时间（毫秒）
    pub batch_timeout_ms: u64,
}

impl Default for BatchConfig {
    fn default() -> Self {
        Self {
            batch_size: 512,
            batch_timeout_ms: 5000,
        }
    }
}

// =============================================================================
// 日志配置
// =============================================================================

/// 日志配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    /// 日志级别 (trace/debug/info/warn/error)
    pub level: String,
    /// 日志格式 (json/text)
    pub format: String,
    /// 输出目标 (console/file/both)
    pub output: String,
    /// 日志文件路径
    pub file_path: Option<String>,
    /// 日志轮转配置
    pub rotation: Option<LogRotationConfig>,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: "info".to_string(),
            format: "json".to_string(),
            output: "console".to_string(),
            file_path: None,
            rotation: None,
        }
    }
}

/// 日志轮转配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogRotationConfig {
    /// 最大文件大小（MB）
    pub max_size_mb: u64,
    /// 保留文件数量
    pub max_files: u32,
    /// 是否压缩旧文件
    pub compress: bool,
}

// =============================================================================
// 安全配置
// =============================================================================

/// 安全配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    /// 是否启用安全功能
    pub enabled: bool,
    /// 认证配置
    pub authentication: Option<AuthenticationConfig>,
    /// 授权配置
    pub authorization: Option<AuthorizationConfig>,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            authentication: None,
            authorization: None,
        }
    }
}

/// 认证配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthenticationConfig {
    /// 认证类型 (jwt/oauth2/basic)
    pub auth_type: String,
    /// JWT配置
    pub jwt: Option<JwtConfig>,
}

/// JWT配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JwtConfig {
    /// 密钥
    pub secret: String,
    /// 过期时间（秒）
    pub expires_in_seconds: u64,
    /// 发布者
    pub issuer: Option<String>,
}

/// 授权配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorizationConfig {
    /// 授权类型 (rbac/abac)
    pub authz_type: String,
    /// 权限配置
    pub permissions: Vec<PermissionConfig>,
}

/// 权限配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionConfig {
    /// 资源
    pub resource: String,
    /// 操作
    pub actions: Vec<String>,
    /// 角色
    pub roles: Vec<String>,
}

// =============================================================================
// 网关配置
// =============================================================================

/// 网关配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GatewayConfig {
    /// 是否启用网关
    pub enabled: bool,
    /// 路由配置
    pub routes: Vec<RouteConfig>,
    /// 过滤器配置
    pub filters: FilterConfig,
    /// 限流配置
    pub rate_limit: RateLimitConfig,
}

impl Default for GatewayConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            routes: Vec::new(),
            filters: FilterConfig::default(),
            rate_limit: RateLimitConfig::default(),
        }
    }
}

/// 路由配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteConfig {
    /// 路径前缀
    pub path_prefix: String,
    /// 目标服务名
    pub service_name: String,
    /// 是否重写路径
    pub rewrite_path: bool,
    /// 超时时间（毫秒）
    pub timeout_ms: Option<u64>,
}

/// 过滤器配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FilterConfig {
    /// 认证过滤器
    pub auth: Option<AuthFilterConfig>,
    /// 日志过滤器
    pub logging: LogFilterConfig,
}

impl Default for FilterConfig {
    fn default() -> Self {
        Self {
            auth: None,
            logging: LogFilterConfig::default(),
        }
    }
}

/// 认证过滤器配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthFilterConfig {
    /// 是否启用
    pub enabled: bool,
    /// 跳过路径
    pub skip_paths: Vec<String>,
}

/// 日志过滤器配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogFilterConfig {
    /// 是否启用请求日志
    pub request_logging: bool,
    /// 是否启用响应日志
    pub response_logging: bool,
    /// 是否记录请求体
    pub log_request_body: bool,
    /// 是否记录响应体
    pub log_response_body: bool,
}

impl Default for LogFilterConfig {
    fn default() -> Self {
        Self {
            request_logging: true,
            response_logging: true,
            log_request_body: false,
            log_response_body: false,
        }
    }
}

/// 限流配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitConfig {
    /// 是否启用限流
    pub enabled: bool,
    /// 全局限流
    pub global: Option<RateLimitRule>,
    /// 按服务限流
    pub per_service: HashMap<String, RateLimitRule>,
    /// 按用户限流
    pub per_user: Option<RateLimitRule>,
    /// 按IP限流
    pub per_ip: Option<RateLimitRule>,
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            global: None,
            per_service: HashMap::new(),
            per_user: None,
            per_ip: None,
        }
    }
}

/// 限流规则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitRule {
    /// 请求速率（请求/秒）
    pub requests_per_second: u32,
    /// 突发请求数
    pub burst_size: u32,
}

// =============================================================================
// 配置验证和构建器
// =============================================================================

impl UnifiedConfig {
    /// 验证配置的有效性
    pub fn validate(&self) -> Result<(), String> {
        // 验证服务名称
        if self.service.name.is_empty() {
            return Err("服务名称不能为空".to_string());
        }

        // 验证端口
        if self.network.port == 0 {
            return Err("服务端口不能为0".to_string());
        }

        // 验证注册中心地址
        if self.registry.endpoints.is_empty() {
            return Err("注册中心地址不能为空".to_string());
        }

        // 验证负载均衡策略
        // 根据策略验证相关配置

        Ok(())
    }

    /// 从环境变量更新配置
    pub fn update_from_env(&mut self) -> Result<(), String> {
        use std::env;

        // 更新服务配置
        if let Ok(name) = env::var("RUSTCLOUD_SERVICE_NAME") {
            self.service.name = name;
        }
        
        if let Ok(version) = env::var("RUSTCLOUD_SERVICE_VERSION") {
            self.service.version = version;
        }

        // 更新网络配置
        if let Ok(port) = env::var("RUSTCLOUD_SERVICE_PORT") {
            self.network.port = port.parse().map_err(|_| "无效的端口号")?;
        }

        // 更新注册中心配置
        if let Ok(registry_type) = env::var("RUSTCLOUD_REGISTRY_TYPE") {
            self.registry.registry_type = registry_type;
        }

        if let Ok(endpoints) = env::var("RUSTCLOUD_REGISTRY_ENDPOINTS") {
            self.registry.endpoints = endpoints
                .split(',')
                .map(|s| s.trim().to_string())
                .collect();
        }

        // 更新日志配置
        if let Ok(log_level) = env::var("RUSTCLOUD_LOG_LEVEL") {
            self.logging.level = log_level;
        }

        Ok(())
    }
}